package com.xxl.job.executor.protocol;

import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.executor.SpringContextUtil;
import com.xxl.job.executor.common.RedisKeyConstant;
import com.xxl.job.executor.constant.FireConstant;
import com.xxl.job.executor.model.CurrentInfoXfModel;
import com.xxl.job.executor.model.SignalDefXfModel;
import com.xxl.job.executor.service.FireCollectService;
import com.xxl.job.executor.utils.*;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONStringer;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

public class XfTCPProtocol {
    private String inetHost = null;
    private int inetPort;
    private String gatherId;
    private String gatherResId;
    private Socket socket;
    private ServerThread currentThread;
    ServerSocket serverSocket;
    private boolean isFinished;

    public XfTCPProtocol() {
    }

    public XfTCPProtocol(String inetHost, int inetPort, String gatherId, String gatherResId) {
        this.inetHost = inetHost;
        this.inetPort = inetPort;
        this.gatherId = gatherId;
        this.gatherResId = gatherResId;
    }

    public void sever() {
        isFinished = false;
        try {
            //创建服务器套接字，绑定到指定的端口
            serverSocket = new ServerSocket(55000);

            //等待客户端连接
            while (!isFinished) {
                Socket socket = serverSocket.accept();//接受连接
                XxlJobLogger.log("创建 <" + inetHost + " TCPProtocol> 成功，等待接收数据 ");

//              if (currentThread != null) {
//                  currentThread.exit=true; // 修改采集线程最外层循环条件为false
//                  currentThread.close();   // 断开io流等资源
//                  XxlJobLogger.log("------------------------准备关闭线程：" + currentThread.getName() + "---------------------------");
//              }

                //创建线程处理连接
                ServerThread socketThread = new ServerThread(socket);
                socketThread.start();
                XxlJobLogger.log("------------------------开启新线程:" + socketThread.getName() + ";地址=>" + socket.getInetAddress() + ":" + socket.getPort() + "---------------------------");
            }
        } catch (IOException e) {
            isFinished = true;
            e.printStackTrace();
        }
    }

    /**
     * 校验和
     *
     * @param hexdata
     * @return
     */
    public static boolean check2binaryString(String hexdata) {
        String substr = hexdata.substring(4, hexdata.length() - 6);//控制单元中各字节数据(第3～27字节)及应用数据单元数据
        String checkSum = hexdata.substring(hexdata.length() - 6, hexdata.length() - 4);//校验和(1字节)
        String sum = TransUtils.makeChecksums(substr);//求和
        if (sum.equals(checkSum)) {
            return true;
        }
        return false;
    }


    class ServerThread extends Thread {

        private Socket client;
        private InputStream in;
        private OutputStream out;
        //volatile修饰符用来保证其它线程读取的总是该变量的最新的值
        //public volatile boolean exit = false;

        public ServerThread(Socket client) {
            this.client = client;

            try {
                in = this.client.getInputStream();
                out = this.client.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        void close() {
            try {
                if (in != null) {
                    in.close();
                    XxlJobLogger.log("------------------- 输入流关闭 --------------------------------");
                }

                if (out != null) {
                    out.close();
                    XxlJobLogger.log("------------------- 输出流关闭 --------------------------------");
                }

                if (client != null) {
                    client.close();
                    XxlJobLogger.log("------------------- 客户端关闭 --------------------------------");
                }
            } catch (Exception e) {
                XxlJobLogger.log("异常数据：" + e.getMessage());
                e.printStackTrace();
            }
        }

        @SneakyThrows
        @Override
        public void run() {
            XxlJobLogger.log("-------------------线程：" + getName() + "--------------------------------");
            int iMaxLenth = 2;
            String lastMessage="";

//            int count=0;
//            LocalDateTime oldTime=null;
//            LocalDateTime newTime=null;
//
//            DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            // 最外层循环用以保证数据的不断读取
            while (true) {
                String recvMessage = "";
                int iRecvMessageLen = 0;

                if (in == null) {
                    XxlJobLogger.log("-------------------输入流为空，线程退出--------------------------------");
                    return;
                }

                try {
                    // 通过循环获取整段信号数据
                    while (true) {
                        byte[] bString = new byte[iMaxLenth];
//                      DataInputStream input = new DataInputStream(in);
                        int i = in.read(bString);
                        iRecvMessageLen += i;
                        String str = ByteUtil.bytes2hexStr(bString);
                        recvMessage += ByteUtil.bytes2hexStr(bString);
                        XxlJobLogger.log("接收报文："+str);
                        if (!recvMessage.startsWith("4040")) {
                            recvMessage = "";
                            break;
                        }

                        if (recvMessage.equals("000000000000000000000000000000000000000000000000000000000000000000000000")) {
                            recvMessage = "";
                            break;
                        }

                        if (str.endsWith("2323") && iRecvMessageLen > 20) {
                            break;
                        }

                        if (str.endsWith("2323") && iRecvMessageLen <= 20) {
                            XxlJobLogger.log("特殊时间点数据:" + recvMessage);
                        }
                    }

                    if (iRecvMessageLen != -1) {
                        byte[] bTemp = ByteUtil.hexStr2bytes(recvMessage);
                        byte[] bRecvMessage = new byte[iRecvMessageLen];
                        System.arraycopy(bTemp, 0, bRecvMessage, 0, iRecvMessageLen);

                        byte[] retByte = bRecvMessage;
                        String retStr = TransUtils.getBufHexStr(retByte);

                        String answerStr = "";

                        XxlJobLogger.log("字段长度："+retStr.length());

                        XxlJobLogger.log(DateUtil.getDate("yyyy-MM-dd HH:mm:ss") + " ; " + retStr);
                        if (retStr != null && !retStr.equals("")) {
                            if (!check2binaryString(retStr)) {
                                //对控制命令和发送信息的否认回答
                                answerStr = answerCommand(retStr.substring(4, 8), FireConstant.KZDYML6);
                                XxlJobLogger.log("---信息否认回答---");
                            } else {
                                String commandStr = retStr.substring(52, 54);//命令字节
                                String Serial = retStr.substring(4, 8); //流水号
                                XxlJobLogger.log("commandStr:" + commandStr);
                                switch (commandStr) {
                                    case FireConstant.KZDYML1://控制命令
                                        answerStr = answerCommand(Serial, FireConstant.KZDYML3);//对控制命令进行确认
                                        break;
                                    case FireConstant.KZDYML2://发送数据
                                        answerStr = answerCommand(Serial, FireConstant.KZDYML3);//对发送数据进行确认
                                        break;
                                    case FireConstant.KZDYML3://确认
                                        break;
                                    case FireConstant.KZDYML4://请求
                                        answerStr = answerCommand(Serial, FireConstant.KZDYML5);//对请求查询命令进行应答
                                        break;
                                    case FireConstant.KZDYML5://应答
                                        answerStr = answerCommand(Serial, FireConstant.KZDYML3);//对发送数据进行确认
                                        break;
                                    case FireConstant.KZDYML6://否认
                                        break;
                                    default:
                                        break;
                                }
                            }
                            byte[] sendInfo = TransUtils.getHexBytes(answerStr);

                            if (retStr.indexOf("040002190100") == -1) {
                                XxlJobLogger.log("answerStr:" + answerStr);
                            }

                            try {
                                out.write(sendInfo);
                                out.flush();
                            } catch (IOException e) {
                                XxlJobLogger.log("☆IO流写入失败！☆");
                                e.printStackTrace();
                            }

                            String dataType = retStr.substring(54, 56);//类型标志
                            String objectNums = retStr.substring(56, 58);//信息对象数目
                            String deviceType = retStr.substring(58, 60);//系统类型
                            String systemAddr = retStr.substring(60, 62); //系统地址


                            //如果是【建筑消防设施部件运行状态】
                            if (Integer.parseInt(dataType, 16) == FireConstant.LXBZ2) {
                                String componentType = retStr.substring(62, 64); //部件类型
                                String componentAddr = retStr.substring(64, 72);//部件地址
                                componentAddr = addressParse(componentAddr);
                                XxlJobLogger.log("componentType:" + componentType);

                                String machineCode = String.format("%09d", Integer.parseInt(componentAddr)).substring(0, 3); //获取机器号
                                String loop = String.format("%09d", Integer.parseInt(componentAddr)).substring(3, 6);         //回路
                                String deviceAddress = String.format("%09d", Integer.parseInt(componentAddr)).substring(6, 9);//设备地址

                                XxlJobLogger.log("machineCode:" + Integer.valueOf(machineCode)); //机器号
                                XxlJobLogger.log("loop:" + Integer.valueOf(loop)); //回路
                                XxlJobLogger.log("deviceAddress:" + Integer.valueOf(deviceAddress)); //设备地址

                                String componentStatus = retStr.substring(72, 76);//部件状态
                                XxlJobLogger.log("componentStatus:" + componentStatus);

                                // 解析部件状态
                                String binaryString = TransUtils.hexString2binaryString(componentStatus.substring(2, 4)) + "" +
                                        TransUtils.hexString2binaryString(componentStatus.substring(0, 2));
                                XxlJobLogger.log("指令:" + binaryString);

                                if ("17".equals(componentType) || "2A".equals(componentType) || "57".equals(componentType)) { //感烟探测器 或 17手报 或电气火灾 或声光报警
                                    XxlJobLogger.log("---2A感烟探测器 或 17手报 或57电气火灾、声光报警---");

                                    if ("1".equals(binaryString.charAt(0) + "")) { //恢复操作
                                        SignalDefXfModel signalDz = new SignalDefXfModel();
                                        signalDz.setGatherId(gatherId);
                                        signalDz.setGatherResId(gatherResId);
                                        signalDz.setSignalValue("0");
                                        signalDz.setRegisterAddr(Integer.valueOf(machineCode).toString());
                                        signalDz.setModuleAddr(Integer.valueOf(loop).toString());

                                        if ("1".equals(binaryString.charAt(13) + "")) { //存在故障 故障恢复
                                            XxlJobLogger.log("---故障恢复操作---");
                                            signalDz.setPointAddr(Integer.valueOf(deviceAddress) + "_2");
                                            SpringContextUtil.getBean(FireCollectService.class).save(signalDz, 0);
                                        } else if ("1".equals(binaryString.charAt(9) + "")) { //存在反馈 反馈撤销
                                            XxlJobLogger.log("---反馈撤销操作---");
                                            signalDz.setPointAddr(Integer.valueOf(deviceAddress) + "_3");
                                            SpringContextUtil.getBean(FireCollectService.class).save(signalDz, 0);
                                        }

                                        continue;
                                    }

                                    // 火警状态 0-无火警 1-有火警
                                    SignalDefXfModel signalHj = new SignalDefXfModel();
                                    signalHj.setGatherId(gatherId);
                                    signalHj.setGatherResId(gatherResId);
                                    signalHj.setSignalValue(binaryString.charAt(14) + "");
                                    signalHj.setRegisterAddr(Integer.valueOf(machineCode).toString());
                                    signalHj.setModuleAddr(Integer.valueOf(loop).toString());
                                    signalHj.setPointAddr(Integer.valueOf(deviceAddress) + "_1");
                                    SpringContextUtil.getBean(FireCollectService.class).save(signalHj, 0);

                                    // 故障状态 0-无故障 1-有故障
                                    SignalDefXfModel signalGz = new SignalDefXfModel();
                                    signalGz.setGatherId(gatherId);
                                    signalGz.setGatherResId(gatherResId);
                                    signalGz.setSignalValue(binaryString.charAt(13) + "");
                                    signalGz.setRegisterAddr(Integer.valueOf(machineCode).toString());
                                    signalGz.setModuleAddr(Integer.valueOf(loop).toString());
                                    signalGz.setPointAddr(Integer.valueOf(deviceAddress) + "_2");
                                    SpringContextUtil.getBean(FireCollectService.class).save(signalGz, 0);

                                    // 反馈状态 0-无反馈 1-有反馈
                                    SignalDefXfModel signalFk = new SignalDefXfModel();
                                    signalFk.setGatherId(gatherId);
                                    signalFk.setGatherResId(gatherResId);
                                    signalFk.setSignalValue(binaryString.charAt(9) + "");
                                    signalFk.setRegisterAddr(Integer.valueOf(machineCode).toString());
                                    signalFk.setModuleAddr(Integer.valueOf(loop).toString());
                                    signalFk.setPointAddr(Integer.valueOf(deviceAddress) + "_3");
                                    SpringContextUtil.getBean(FireCollectService.class).save(signalFk, 0);

                                    // 电源故障 0-电源正常 1-电源故障
                                    SignalDefXfModel signalDy = new SignalDefXfModel();
                                    signalDy.setGatherId(gatherId);
                                    signalDy.setGatherResId(gatherResId);
                                    signalDy.setSignalValue(binaryString.charAt(7) + "");
                                    signalDy.setRegisterAddr(Integer.valueOf(machineCode).toString());
                                    signalDy.setModuleAddr(Integer.valueOf(loop).toString());
                                    signalDy.setPointAddr(Integer.valueOf(deviceAddress) + "_4");
                                    SpringContextUtil.getBean(FireCollectService.class).save(signalDy, 0);
                                } else if ("8E".equals(componentType) || "8D".equals(componentType)) { //防火门 1-故障 0-正常
                                    XxlJobLogger.log("---防火门设备---");
                                    SignalDefXfModel signalGz = new SignalDefXfModel();
                                    signalGz.setGatherId(gatherId);
                                    signalGz.setGatherResId(gatherResId);

                                    if ("1".equals(binaryString.charAt(0) + "") && "1".equals(binaryString.charAt(13) + "")) { //恢复操作
                                        XxlJobLogger.log("---故障恢复操作---");
                                        signalGz.setSignalValue("0");
                                    } else {
                                        signalGz.setSignalValue(binaryString.charAt(13) + "");
                                    }

                                    signalGz.setRegisterAddr(Integer.valueOf(machineCode).toString());
                                    signalGz.setModuleAddr(Integer.valueOf(loop).toString());
                                    signalGz.setPointAddr(Integer.valueOf(deviceAddress) + "");
                                    SpringContextUtil.getBean(FireCollectService.class).save(signalGz, 0);
                                } else if ("FF".equals(componentType)) { //超细干粉
                                    XxlJobLogger.log("---超细干粉---");
                                    //启停状态 1-启动 0-停止
                                    SignalDefXfModel signalDz = new SignalDefXfModel();
                                    signalDz.setGatherId(gatherId);
                                    signalDz.setGatherResId(gatherResId);

                                    if ("1".equals(binaryString.charAt(1) + "")) { //超细干粉启动状态
                                        signalDz.setSignalValue(binaryString.charAt(10) + "");
                                        signalDz.setRegisterAddr(Integer.valueOf(machineCode).toString());
                                        signalDz.setModuleAddr(Integer.valueOf(loop).toString());
                                        signalDz.setPointAddr(Integer.valueOf(deviceAddress) + "");
                                        SpringContextUtil.getBean(FireCollectService.class).save(signalDz, 0);
                                    }
                                } else if ("00".equals(componentType)) {
                                    if ("1".equals(binaryString.charAt(0) + "")) { //故障恢复与反馈撤销指令
                                        SignalDefXfModel signalDz = new SignalDefXfModel();
                                        signalDz.setGatherId(gatherId);
                                        signalDz.setGatherResId(gatherResId);
                                        signalDz.setSignalValue("0");
                                        signalDz.setRegisterAddr(Integer.valueOf(machineCode).toString());
                                        signalDz.setModuleAddr(Integer.valueOf(loop).toString());

                                        if ("1".equals(binaryString.charAt(13) + "")) { //存在故障 电压探测器故障恢复
                                            XxlJobLogger.log("---故障恢复操作---");
                                            signalDz.setPointAddr(Integer.valueOf(deviceAddress) + "");
                                            SpringContextUtil.getBean(FireCollectService.class).save(signalDz, 0);
                                        } else if ("1".equals(binaryString.charAt(9) + "")) { //存在反馈 电气火灾反馈撤销
                                            XxlJobLogger.log("---反馈撤销操作---");
                                            signalDz.setPointAddr(Integer.valueOf(deviceAddress) + "_3");
                                            SpringContextUtil.getBean(FireCollectService.class).save(signalDz, 0);
                                        }
                                    } else {
                                        // 故障状态 0-无故障 1-有故障
                                        SignalDefXfModel signalGz = new SignalDefXfModel();
                                        signalGz.setGatherId(gatherId);
                                        signalGz.setGatherResId(gatherResId);
                                        signalGz.setSignalValue(binaryString.charAt(13) + "");
                                        signalGz.setRegisterAddr(Integer.valueOf(machineCode).toString());
                                        signalGz.setModuleAddr(Integer.valueOf(loop).toString());
                                        signalGz.setPointAddr(Integer.valueOf(deviceAddress) + "_2");
                                        SpringContextUtil.getBean(FireCollectService.class).save(signalGz, 0);
                                    }
                                } else {
                                    XxlJobLogger.log("☆☆☆ 未知 ☆☆☆");
                                }
                            } else if (Integer.parseInt(dataType, 16) == FireConstant.LXBZ1) {
                                String handleType = retStr.substring(62, 66); //操作标志
                                // 解析部件状态
                                String binaryString = TransUtils.hexString2binaryString(handleType.substring(2, 4)) + "" +
                                        TransUtils.hexString2binaryString(handleType.substring(0, 2));

                            } else if (Integer.parseInt(dataType, 16) == FireConstant.LXBZ4) {
                                String handleType = retStr.substring(62, 64); //操作标志
                                String binaryString = TransUtils.hexString2binaryString(handleType);

                                if ("01".equals(handleType) && "1".equals(binaryString.charAt(7) + "")) {
                                    XxlJobLogger.log("-------------复位操作------------");

//                                    oldTime=oldTime.plusSeconds(20);
//                                    XxlJobLogger.log("复位后心跳时间："+oldTime.format(dateTimeFormatter));

                                    // *号 必须要加，否则无法模糊查询
                                    String prefix = "XF_CURRENT_XF-*";
                                    // 获取所有的key
                                    Set<String> keys = SpringContextUtil.getBean(StringRedisTemplate.class).keys(prefix);

                                    List<List<CurrentInfoXfModel>> dataList = new ArrayList();
                                    // 批量获取所有风机数据
                                    for (String s : keys) {
                                        List<CurrentInfoXfModel> redisCurrentCode = new ArrayList<>();
                                        BoundHashOperations<String, String, String> valueOperations = SpringContextUtil.getBean(StringRedisTemplate.class).boundHashOps(s);
                                        List<String> sigDefModelJsonList = MapUtil.getLikeByMap(valueOperations.entries());
                                        if (sigDefModelJsonList != null) {
                                            for (String sigDefModelStr : sigDefModelJsonList) {
                                                if (StringUtils.isNotBlank(sigDefModelStr)) {
                                                    try {
                                                        CurrentInfoXfModel currentInfoXfModel = JSONUtils.json2pojo(sigDefModelStr, CurrentInfoXfModel.class);
                                                        if ("9010005".equals(currentInfoXfModel.getGatherId()) && "1".equals(currentInfoXfModel.getValue())) {
                                                            redisCurrentCode.add(currentInfoXfModel);
                                                        }
                                                    } catch (IOException e) {
                                                        //LOGGER.error("终端JSON='{}' 转换异常！", sigDefModelStr, e);
                                                        XxlJobLogger.log("终端JSON='{" + sigDefModelStr + "}' 转换异常！");
                                                    }
                                                }
                                            }

                                            if (redisCurrentCode.size() > 0) {
                                                dataList.add(redisCurrentCode);
                                            }
                                        }
                                    }

                                    String nDate = "";
                                    nDate = ThreadLocalDateUtil.formatDate(new Date());

                                    for (List<CurrentInfoXfModel> list : dataList) {
                                        for (CurrentInfoXfModel model : list) {

                                            if ("DF".equals(model.getSignalType()) && "1".equals(model.getValue())) {
                                                continue;
                                            }

                                            model.setValue("0");
                                            model.setSendTime(ThreadLocalDateUtil.formatDate(new Date()));
                                            //实时数据存入redis
                                            BoundHashOperations<String, String, String> valueOperations = SpringContextUtil.getBean(StringRedisTemplate.class).boundHashOps(RedisKeyConstant.XF_CURRENT + model.getDevCode());
                                            valueOperations.put(model.getSignalCode(),
                                                    new JSONStringer().object()
                                                            .key("signalCode").value(model.getSignalCode())
                                                            .key("gatherResId").value(model.getGatherResId())
                                                            .key("gatherId").value(model.getGatherId())
                                                            .key("signalName").value(model.getSignalName())
                                                            .key("signalType").value(model.getSignalType())
                                                            .key("value").value(model.getValue())
                                                            .key("valunit").value(model.getValunit())
                                                            .key("devCode").value(model.getDevCode())
                                                            .key("time").value(nDate)
                                                            .key("lastTime").value(model.getLastTime())
                                                            .key("pointAddr").value(model.getPointAddr())
                                                            .key("sendTime").value(model.getSendTime())
                                                            .endObject().toString());
                                        }
                                    }
                                    XxlJobLogger.log("-------------复位结束------------");
                                }
                            }
                        }

                        // 字符串第一次被使用
                        if("".equals(lastMessage)){
                            if(retStr.length()!=68){
                                lastMessage=retStr;
                                XxlJobLogger.log("lastMessage初始化："+lastMessage);
                            }
                        }else{
                            if(retStr.length()!=68){
                                if(lastMessage.equals(retStr)){
                                    XxlJobLogger.log("发现重复数据："+retStr);
                                    XxlJobLogger.log("lastMessage初始化为空");
                                    lastMessage="";

                                    // 关闭连接
                                    close();

                                    // 退出最外层循环,也意味着该线程内容执行完毕
                                    break;

                                }else{
                                    lastMessage=retStr;
                                    XxlJobLogger.log("lastMessage刷新："+lastMessage);
                                }
                            }
                        }

                        // 心跳数据
//                        if(retStr.length()==68){
//                            oldTime=LocalDateTime.now();
//                        }else{
//                            if(oldTime==null){
//                                oldTime=LocalDateTime.now();
//                            }
//                            newTime=LocalDateTime.now();
//
//                            // 比较新旧心跳时间差
//                            XxlJobLogger.log("-------比较-------");
//                            XxlJobLogger.log(oldTime.format(dateTimeFormatter));
//                            XxlJobLogger.log(newTime.format(dateTimeFormatter));
//                            XxlJobLogger.log("时间差值："+Duration.between(oldTime,newTime).toMillis());
//
//                            long mills=Duration.between(oldTime,newTime).toMillis();
//                            if(count>1 && mills>10200){
//                                XxlJobLogger.log("【触发断开重连机制】");
//
////                                // 接收数据长度为-1，用以表示client程序断开，此时，释放资源
////                                close();
////
////                                // 退出最外层循环,也意味着该线程内容执行完毕
////                                break;
//                            }else{
//                                XxlJobLogger.log("没有触发断开重连机制");
//                            }
//                        }
//
//                        count=count+1;
                        XxlJobLogger.log("-------------------------------------------------------------------");
//                        if(count>10){
//                            XxlJobLogger.log("10次断开重连测试");
//
//                            // 接收数据长度为-1，用以表示client程序断开，此时，释放资源
//                            close();
//
//                            // 退出最外层循环,也意味着该线程内容执行完毕
//                            break;
//                        }
                    } else {
                        XxlJobLogger.log("接收数据长度为-1，开始执行客户端断开操作");

                        // 接收数据长度为-1，用以表示client程序断开，此时，释放资源
                        close();

                        // 退出最外层循环,也意味着该线程内容执行完毕
                        break;
                    }
                } catch (Exception e) {
                    XxlJobLogger.log("发生异常：" + e.getMessage());
                    XxlJobLogger.log("异常出现，开始执行客户端断开操作");
                    e.printStackTrace();
                    close(); //如果发生异常，关闭该线程所有资源以及socket连接

                    break; // 退出最外层循环,也意味着该线程内容执行完毕
                }
            }
        }

        /**
         * 解析部件地址
         **/
        public String addressParse(String componentAddr) {
            return String.valueOf(Integer.parseInt(componentAddr.substring(6, 8) + "" +
                    componentAddr.substring(4, 6) + "" +
                    componentAddr.substring(2, 4) + "" +
                    componentAddr.substring(0, 2), 16));
        }
    }

    /**
     * 应答命令
     */
    public static String answerCommand(String Serial, String commandStr) {
        //String Serial = hexdata.substring(4,2); 57F80B540200 90F70B540200
        String str = Serial +  //业务流水号
                "0102" + //协议版本号
                DateUtil.hexDateString() + //时间标签
                "90F70B540200" +  //源地址
                "500000000000" + //目的地址
                "0000" +     //应用数据单元长度
                commandStr;    //命令字节
//        System.out.println("commandStr:  "+commandStr);
        String answerStr = "4040" + str + TransUtils.makeChecksums(str) + "2323";
        return answerStr;
    }
}
